package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.enums.DomainIsDeleteStatusEnum;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.hosp.utils.DateUtil;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA
 *
 * @Date: 2022/12/21 - 16:14
 * @Author: Hyoung
 * @Description:
 */
@Service
@Slf4j
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> paramMap) {
        // 数据转换
        String jsonString = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(jsonString, Schedule.class);

        // 判断医院是否存在
        Hospital hospital = hospitalRepository.findByHoscode(schedule.getHoscode());
        if (hospital == null) {
            throw new YyghException(ResultCodeEnum.HOSPITAL_OPEN);
        }

        // 判断排班是否存在
        Schedule existSchedule = scheduleRepository.findByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        if (existSchedule != null) {
            schedule.setId(existSchedule.getId());
            schedule.setCreateTime(existSchedule.getCreateTime());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(DomainIsDeleteStatusEnum.UNDELETED.getIsDelete());
            scheduleRepository.save(schedule);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(DomainIsDeleteStatusEnum.UNDELETED.getIsDelete());
            scheduleRepository.save(schedule);
        }
    }

    @Override
    public Page<Schedule> selectPage(int page, int limit, String hoscode) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageable = PageRequest.of(page - 1, limit, sort);
        Schedule schedule = new Schedule();
        schedule.setHoscode(hoscode);
        schedule.setIsDeleted(DomainIsDeleteStatusEnum.UNDELETED.getIsDelete()); // 0考虑逻辑删除
        Example<Schedule> example = Example.of(schedule);
        Page<Schedule> pages = scheduleRepository.findAll(example, pageable);
        return pages;
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.findByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        // 这里使用的逻辑删除
        schedule.setIsDeleted(DomainIsDeleteStatusEnum.DELETED.getIsDelete());
        scheduleRepository.save(schedule);
    }

    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        return scheduleRepository.findByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());
    }


    @Override
    public Map<String, Object> getRuleSchedule(Long page, Long limit, String hoscode, String depcode) {

        // TODO 组装list
        //查询条件：根据医院编号和科室编号查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("isDeleted").is(0);
        // 过滤，分组，统计，分页，排序
        Aggregation aggregation = Aggregation.newAggregation(
                //  参数组装
                // 过滤
                Aggregation.match(criteria),
                // 分组
                // group: 指定分组条件
                // first： 指定在schedule集合中要查询的字段
                // as： 指定在BookingScheduleRuleVo集合中要填充的字段
                Aggregation.group("workDate").first("workDate").as("workDate")
                        // 统计
                        .count().as("docCount") // 医生人数当天的排班数量，count当前分组下记录的个数 as 将统计后的记录的个数填充到BookingScheduleRuleVo对象中
                        .sum("reservedNumber").as("reservedNumber") // 可预约数量 sum统计当前分组下Schedule集合中reservedNumber数据之和 as 将统计后的结果填充到BookingScheduleRuleVo对象中的reservedNumber属性
                        .sum("availableNumber").as("availableNumber") // 剩余数量
                // 排序 根据时间正序排
                , Aggregation.sort(Sort.Direction.ASC, "workDate")
                // 分页 skip：偏移量 从0开始
                , Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)

        );
        // 将从schedule集合中查询的数据，根据排班日期分组统计到BookingScheduleRuleVo中
        AggregationResults<BookingScheduleRuleVo> aggregate =
                mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> list = aggregate.getMappedResults(); // 这个是我们最重要的数据

        // 计算total
        Aggregation totalAgg = Aggregation.newAggregation(Aggregation.match(criteria), Aggregation.group("workDate"));
        AggregationResults<BookingScheduleRuleVo> totalAggResults = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();
        for (BookingScheduleRuleVo bookingScheduleRuleVo : list) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = DateUtil.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }


        // TODO 计算total
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("total", total);
        return map;
    }

    /**
     * 根据日期对象和时间字符串获取一个日期时间对象
     *
     * @param dateTime
     * @param timeString
     * @return
     */
    private DateTime getDateTime(DateTime dateTime, String timeString) {

        String dateTimeString = dateTime.toString("yyyy-MM-dd") + " " + timeString;
        return DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
    }


    /**
     * 根据预约规则获取可预约日期列表
     */
    private List<Date> getDateList(BookingRule bookingRule) {

        //预约周期
        int cycle = bookingRule.getCycle();

        //当天放号时间
        DateTime releaseTime = this.getDateTime(new DateTime(), bookingRule.getReleaseTime());

        //如果当天放号时间已过，则预约周期后一天显示即将放号，周期加1
        if (releaseTime.isBeforeNow()) {
            cycle += 1;
        }

        //计算当前可显示的预约日期，并且最后一天显示即将放号倒计时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            //计算当前可显示的预约日期
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }

        return dateList;
    }


    @Override
    public void updateByOrderMqVo(OrderMqVo orderMqVo) {
        log.info("数据同步");
        Schedule schedule = scheduleRepository.findById(orderMqVo.getScheduleId()).get();
        schedule.setReservedNumber(orderMqVo.getReservedNumber());
        schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
        schedule.setUpdateTime(new Date());

        // 主键一致就是更新
        scheduleRepository.save(schedule);
    }

    /**
     * 组装Schedule信息，用于订单的创建
     *
     * @param scheduleId
     * @return
     */
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {

        Schedule schedule = this.getDetailById(scheduleId);

        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        scheduleOrderVo.setHoscode(schedule.getHoscode()); //医院编号
        scheduleOrderVo.setHosname((String) schedule.getParam().get("hosname")); //医院名称
        scheduleOrderVo.setDepcode(schedule.getDepcode()); //科室编号
        scheduleOrderVo.setDepname((String) schedule.getParam().get("depname")); //科室名称

        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId()); //医院端的排班主键
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber()); //剩余预约数
        scheduleOrderVo.setTitle(schedule.getTitle()); //医生职称
        scheduleOrderVo.setReserveDate(schedule.getWorkDate()); //安排日期
        scheduleOrderVo.setReserveTime(schedule.getWorkTime()); //安排时间（0：上午 1：下午）
        scheduleOrderVo.setAmount(schedule.getAmount());//挂号费用

        //获取预约规则相关数据
        Hospital hospital = hospitalRepository.findByHoscode(schedule.getHoscode());
        BookingRule bookingRule = hospital.getBookingRule();
        String quitTime = bookingRule.getQuitTime();//退号时间

        //退号实际时间（如：就诊前一天为-1，当天为0）
        DateTime quitDay = new DateTime(schedule.getWorkDate()).plusDays(bookingRule.getQuitDay());//退号日期
        DateTime quitDateTime = this.getDateTime(quitDay, quitTime);//可退号的具体的日期和时间
        scheduleOrderVo.setQuitTime(quitDateTime.toDate());

        return scheduleOrderVo;
    }

    /**
     * 获取预约详情
     *
     * @param id
     * @return
     */
    @Override
    public Schedule getDetailById(String id) {

        Schedule schedule = scheduleRepository.findById(id).get();
        return this.packSchedule(schedule);
    }

    /**
     * 封装医院名称，科室名称和周几
     *
     * @param schedule
     * @return
     */
    private Schedule packSchedule(Schedule schedule) {
        //医院名称
        String hosname = hospitalRepository.findByHoscode(schedule.getHoscode()).getHosname();
        //科室名称
        String depname = departmentRepository.findByHoscodeAndDepcode(schedule.getHoscode(), schedule.getDepcode()).getDepname();
        //周几
        String dayOfWeek = DateUtil.getDayOfWeek(new DateTime(schedule.getWorkDate()));
        schedule.getParam().put("hosname", hosname);
        schedule.getParam().put("depname", depname);
        schedule.getParam().put("dayOfWeek", dayOfWeek);
        return schedule;
    }

    /**
     * 获取可预约排班日期数据
     *
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> getBookingScheduleRule(String hoscode, String depcode) {

        //获取医院
        Hospital hospital = hospitalRepository.findByHoscode(hoscode);
        //获取预约规则
        BookingRule bookingRule = hospital.getBookingRule();

        //根据预约规则获取可预约日期列表
        List<Date> dateList = this.getDateList(bookingRule);

        //查询条件：根据医院编号、科室编号以及预约日期查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
        //根据工作日workDate期进行分组
        Aggregation agg = Aggregation.newAggregation(
                //1 查询条件
                Aggregation.match(criteria),
                Aggregation
                        //2 按照日期分组 select workDate as workDate from schedule group by workDate
                        .group("workDate").first("workDate").as("workDate")
                        //3 医生人数
                        .count().as("docCount")
                        //4 可预约数
                        .sum("reservedNumber").as("reservedNumber")
                        //5 剩余预约数
                        .sum("availableNumber").as("availableNumber")
        );

        //执行查询
        AggregationResults<BookingScheduleRuleVo> aggResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        //获取查询结果
        List<BookingScheduleRuleVo> list = aggResults.getMappedResults();

        //将list转换成Map，日期为key，BookingScheduleRuleVo对象为value
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(list)) {
            scheduleVoMap = list.stream().collect(
                    Collectors.toMap(BookingScheduleRuleVo::getWorkDate, bookingScheduleRuleVo -> bookingScheduleRuleVo)
            );
        }

        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        int size = dateList.size();
        for (int i = 0; i < size; i++) {

            Date date = dateList.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);

            if (bookingScheduleRuleVo == null) { // 说明当天没有排班数据
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                bookingScheduleRuleVo.setWorkDate(date);
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }

            bookingScheduleRuleVo.setWorkDateMd(date);

            //计算当前预约日期为周几
            String dayOfWeek = DateUtil.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            if (i == size - 1) { //最后一条记录为即将放号
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0); // 正常
            }

            //设置预约状态： 0正常； 1即将放号； -1当天已停止挂号
            if (i == 0) { //当天如果过了停挂时间， 则不能挂号
                DateTime stopTime = this.getDateTime(new DateTime(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    bookingScheduleRuleVo.setStatus(-1);//停止挂号
                }
            }

            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        //医院基本信息
        Map<String, String> info = new HashMap<>();
        //医院名称
        info.put("hosname", hospitalRepository.findByHoscode(hoscode).getHosname());
        //科室
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        //大科室名称
        info.put("bigname", department.getBigname());
        //科室名称
        info.put("depname", department.getDepname());
        //当前月份
        info.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        info.put("releaseTime", bookingRule.getReleaseTime());

        Map<String, Object> result = new HashMap<>();
        //可预约日期数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);//排班日期列表
        result.put("info", info);//医院基本信息
        return result;
    }

}
